import { _decorator, Camera, CCFloat, Component, EventTouch, Input, input, Layers, Node, PhysicsSystem2D, tween, v2, v3, Vec2, Vec3, view } from 'cc';
import { EventManager, } from '../event/EventManager';
const { ccclass, property } = _decorator;

@ccclass('VillageCamera')
export class VillageCamera extends Component {

    public static instance: VillageCamera;


    /**最大的聚焦 */
    private maxOrtho: number = 1200
    /**最小的聚焦 */
    private minOrtho: number = 700
    /**最大的移动距离X */
    private maxMoveX: number = 800
    /**最大的移动距离Y */
    private maxMoveY: number = 400
    /**地图的宽度 */
    private mapWidth: number = 3700
    /**地图的高度 */
    private mapHeight: number = 2600
    /**设计分辨率宽度 */
    private viewWidth: number = 750
    /**设计分辨率高度 */
    private viewHeight: number = 1400

    protected onLoad(): void {
        VillageCamera.instance = this
    }


    public speed: number = 1;
    public camera: Camera;

    private startX: number = 0;
    private startY: number = 0;

    start() {
        console.log(this.node.position)
        console.log(this.node.worldPosition)

        let size = view.getDesignResolutionSize()
        this.viewHeight = size.height
        this.viewWidth = size.width

        this.camera = this.node.getComponent(Camera)

        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    protected onDisable(): void {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    onTouchStart(event: EventTouch) {
        this.startX = event.getLocationX()
        this.startY = event.getLocationY()
    }

    onTouchMove(event: EventTouch) {


        let touches = event.getAllTouches()
        if (touches.length == 1) {
            let pre = event.getPreviousLocation()
            let now = v2(event.getLocationX(), event.getLocationY())
            let offset = v2(0, 0)
            Vec2.subtract(offset, now, pre)

            this.speed = this.camera.orthoHeight * (1 / 700)

            this.node.translate(v3(- offset.x * this.speed, -offset.y * this.speed, 0))

            let newPos = this.limitPosition(this.node.position)
            this.node.setPosition(newPos)

             

        } else {
            let a = touches[0]
            let b = touches[1]
            let preDistance = Vec2.distance(a.getPreviousLocation(), b.getPreviousLocation())

            let nowDistance = Vec2.distance(a.getLocation(), b.getLocation())

            let orthoHeight = 0

            if (preDistance == nowDistance) {
                return
            }
            if (preDistance > nowDistance) {

                //放大
                orthoHeight = this.camera.orthoHeight + this.camera.orthoHeight * (10 / 700)
            } else {

                //缩小
                orthoHeight = this.camera.orthoHeight - this.camera.orthoHeight * (10 / 700)
            }

            if (orthoHeight < this.minOrtho) {
                orthoHeight = this.minOrtho
            }
            if (orthoHeight > this.maxOrtho) {
                orthoHeight = this.maxOrtho
            }
            this.camera.orthoHeight = orthoHeight

        }

    }

    onTouchEnd(event: EventTouch) {


        let touches = event.getAllTouches()
        if (touches.length > 0) {
            return
        }

        let x = event.getLocationX()
        let y = event.getLocationY()
        let distance = Vec2.distance(v2(this.startX, this.startY), v2(x, y))
        if (Math.abs(distance) < 10) {
            let temp = v3(0, 0, 0)
            this.camera.screenToWorld(v3(event.getLocationX(), event.getLocationY(), 0), temp)

            const collider = PhysicsSystem2D.instance.testPoint(v2(temp.x, temp.y));


            if (collider.length == 0) {
                return
            }

            if (collider.length == 1) {
                EventManager.instance.emit(EventManager.EventType.BGCLICK, collider[0].node)
                return
            }

            for (let col of collider) {
                if (col.node.layer == Layers.Enum.Space) {

                    EventManager.instance.emit(EventManager.EventType.SpaceClick, { node: col.node, eventTouch: event })
                }
                if (col.node.layer == Layers.Enum.Wall) {
                    EventManager.instance.emit(EventManager.EventType.WallClick, { node: col.node, eventTouch: event })
                }

            }



        }
    }

    /**
     * 限制相机的位置，在一定的范围内
     * @param pos 
     */
    limitPosition(pos:Vec3): Vec3 {
        let cameraWidth = this.viewWidth / (700 / this.camera.orthoHeight)
        let cameraHeight = this.viewHeight / (700 / this.camera.orthoHeight)

        this.maxMoveX = (this.mapWidth - cameraWidth) / 2
        this.maxMoveY = (this.mapHeight - cameraHeight) / 2


        let newPos = pos.clone()
       
        if (newPos.x < -this.maxMoveX) {

            newPos = v3(-this.maxMoveX, newPos.y, newPos.z)
        }
        if (newPos.x > this.maxMoveX) {

            newPos = v3(this.maxMoveX, newPos.y, newPos.z)
        }
        if (newPos.y < -this.maxMoveY) {

            newPos = v3(newPos.x, -this.maxMoveY, newPos.z)
        }
        if (newPos.y > this.maxMoveY) {

            newPos = v3(newPos.x, this.maxMoveY, newPos.z)
        }
        return newPos
    }

    /**
     * 将相机移动到世界坐标点上
     * @param wpos 
     */
    moveToWorldPos(wpos: Vec3) {
        let offset = this.node.worldPosition.clone().subtract(wpos)
        let targetPos = this.node.position.clone().subtract(offset)

        let newPos = this.limitPosition(targetPos)
        tween(this.node)
            .to(1, { position: new Vec3(newPos.x, newPos.y, newPos.z) })
            .start()
    }


}


